<template>
    <view>
		
		<view class="seven big-cover marboth" :class="{rotate: playing}">
			<image :src="playBarData.cover + '?param=512y512'" mode="aspectFit"></image>
		</view>

        <view class="seven lyricList marboth">
            <ul ref='ul' class="lyricListContent" :style="'margin-top: -' + 49*(lyricIndex - 3) + 'upx'">
                <li class="lyric-size" :style="lyricIndex === index && 'color: red'" v-for="(segment, index) in lyricProcessed" :key="index">{{segment.text}}</li>
            </ul>
        </view>

        <view class="seven text marboth">
            <text class="text-left" v-show="currentTime">{{currentTime}}</text>
			<text class="text-right" v-show="totalTime">{{leftTime}}</text>
        </view>
		
		<view class="seven marboth">
			<slider class="slider" @changing="sliderTabStart" @change="sliderTabEnd" :value="sliderPercentValue" selected-color="red" block-color="red" block-size="16"/>
		</view>
		
		<view class="play-area">
			<play-bar></play-bar>
		</view>

    </view>
</template>

<script>
    import Vuex from 'vuex';
	// 播放栏
	import playBar from "@/components/custom/play-bar.vue";

    export default {
		components: {
			playBar
		},
        data() {
            return {
                // 当前播放时间
                currentTime: '',
                // Audio总时间
                totalTime: '',
				// 剩余时间
				leftTime: '',
                // 滑块百分比整数
                sliderPercentValue: 0,
                // 允许滑块更新值?
                allowSliderValueUpdate: true,
                // 处理过的歌词, 二维数组
                lyricProcessed: [],
                // 当前播放第几条歌词?
                lyricIndex: 0
            }
        },
        computed: {
            ...Vuex.mapState([
                'audio',
				'playing',
                'playBarData',
                'lyricData'
            ])
        },
        mounted() {
			
			console.log('页面已挂载');

            // 改变标题
            uni.setNavigationBarTitle({
                title: `${this.playBarData.artist} - ${this.playBarData.name}`
            });

            // 挂载后如果vuex的lyricData中有原始歌词, 那么执行歌词处理
            if (this.lyricData.lyric) {
                this.processLyric()
            };
			
            // 页面刚挂载歌词需要回到顶部
            this.lyricIndex = 0;
			
            // audio时间数据更新时
            this.audio.onTimeUpdate(this.timeChangeEvent);

            // 页面挂载后快速切换歌词
            this.fastSeekLyric();

            this.audio.onEnded(() => {
				console.log('音频播放结束事件 - playing.vue');
                
                // 改变标题
                uni.setNavigationBarTitle({
                    title: `正在播放: ${this.playBarData.artist} - ${this.playBarData.name}`
                });

                // 歌词回到顶部
                this.lyricIndex = 0;
				this.$refs.ul.style.marginTop = 0;

                // 如果当前有歌词, 那么执行歌词处理
                //if(this.lyricData.lyric) {
                    //console.log(this.lyricData.lyric);
                this.processLyric();
                //};

            })

        },
		// 导航栏按钮tab处理
		onNavigationBarButtonTap(e) {
			//console.log(e);
			// 如果点击的是第二个按钮, toSearch(), 第一个按钮, openDrawer
			if(e.index == 0) {
				this.toIndex();
			}
		},
        methods: {
            toIndex() {
                uni.navigateTo({
					url: '../index/index',
					success: res => {},
					fail: () => {}
				});
            },
            // 时间数据改变需要执行的命令
            timeChangeEvent() {
				//console.log('当前音频播放状态', this.playing);
                // 当前分钟数
                let min = Math.floor(this.audio.currentTime / 60);
                min = min.toString().length === 1 ? ('0' + min) : min;
                // 当前秒钟数
                let sec = Math.round(this.audio.currentTime % 60);
                sec = sec.toString().length === 1 ? ('0' + sec) : sec;
                // 总分钟数
                let minTotal = Math.floor(this.audio.duration / 60);
                minTotal = minTotal.toString().length === 1 ? ('0' + minTotal) : minTotal;
                // 总秒钟数
                let secTotal = Math.round(this.audio.duration % 60);
                secTotal = secTotal.toString().length === 1 ? ('0' + secTotal) : secTotal;
				// 剩余总秒钟数
				let leftTotal = this.audio.duration - this.audio.currentTime;
				let leftSec = Math.round(leftTotal % 60);
				leftSec = leftSec.toString().length === 1 ? ('0' + leftSec) : leftSec;
				let leftMin = Math.floor(leftTotal / 60);
				leftMin = leftSec.toString().length === 1 ? ('0' + leftMin) : leftMin;
				
                
                // 转换当前播放百分比
                let audioPlayPercent = this.audio.currentTime / this.audio.duration * 100;

                // 如果允许更新滑块值(@changing事件为按下滑块时触发, @change事件为松开滑块时触发), 更新, 否则不更新
                if(this.allowSliderValueUpdate) {
                    this.sliderPercentValue = Math.floor(audioPlayPercent)
                };

                // 存储分钟:秒钟格式数据
                this.currentTime = `${min}:${sec}`;
                this.totalTime = `${minTotal}:${secTotal}`;
				this.leftTime = `${leftMin}:${leftSec}`;
                
                // 判断当前应该播放那一条歌词
				if (this.lyricIndex < this.lyricProcessed.length - 2) {
					if(this.currentTime > this.lyricProcessed[this.lyricIndex + 1].time) {
                            this.lyricIndex ++;
                        }
                }
            },
            // 按下滑块时
            sliderTabStart() {
                this.allowSliderValueUpdate = false;
            },
            // 松开滑块时
            sliderTabEnd(e) {
                // 松开滑块时 允许改变滑块值
                this.allowSliderValueUpdate = true;
                // 松开滑块时 计算跳转时间并用seek跳转
                this.audio.seek(e.detail.value / 100 * this.audio.duration);
                // 松开滑块时 

                this.fastSeekLyric();
                
            },
            // 快速切换歌词
            fastSeekLyric() {
                // 当前分钟数
                let min = Math.floor(this.audio.currentTime / 60);
                min = min.toString().length === 1 ? ('0' + min) : min;
                // 当前秒钟数
                let sec = Math.round(this.audio.currentTime % 60);
                sec = sec.toString().length === 1 ? ('0' + sec) : sec;
                // 总分钟数
                let minTotal = Math.floor(this.audio.duration / 60);
                minTotal = minTotal.toString().length === 1 ? ('0' + minTotal) : minTotal;
                // 总秒钟数
                let secTotal = Math.round(this.audio.duration % 60);
                secTotal = secTotal.toString().length === 1 ? ('0' + secTotal) : secTotal;

                let fastCurrentTime = `${min}:${sec}`;

                const that = this;
                this.lyricIndex = 0;
                (function findLyricPositon() {
					if (that.lyricIndex < that.lyricProcessed.length - 2) {
						if(fastCurrentTime > that.lyricProcessed[that.lyricIndex + 1].time) {
                            that.lyricIndex ++;
							findLyricPositon();
                        }
                    }
                })();
            },
            
            // 格式化歌词(处理歌词数据)
            processLyric() {
				// 因为处理歌词是push数据, 如果不清空当前歌词, 会跟写上一首
                this.lyricProcessed = [];
				// 临时存储歌词数据
                let rawLyric = this.lyricData.lyric;
                //console.log(rawLyric);
                // 先用]切割
                let segmentLyric = rawLyric.split('\n');
                // 弹出最后一项无用项
                segmentLyric.pop();

                segmentLyric.forEach( (segment, index) => {
                    // 每段用]切割
                    let temp = segment.split(']');
                    // 第一项时间前面的[切割掉
                    temp[0] = temp[0].substring(1, temp[0].length - 1);
                    // 如果第二项有歌词去除前后空格, 没有赋空
                    temp[1] = temp[1] !== '' ? temp[1].trim() : '---';
                    // 推到数组
                    this.lyricProcessed.push({
                        time: temp[0],
                        text: temp[1]
                    });
                });
				// 增加一项防止时间跳出
// 				this.lyricProcessed.push({
// 					time: "100:00.00",
// 					text: "完"
// 				})
                //console.log(this.lyricProcessed);
            }
        }
    }

</script>

<style>
	
	@keyframes ani-rotate{
		from{transform: rotate(0deg)}
		to{transform: rotate(360deg)}
	}
	
	/* 专辑封面 */
	.big-cover {
	    width: 400upx;
	    height: 400upx;
		animation: ani-rotate 30s linear infinite;
		animation-play-state: paused;
	}
	.rotate {
		animation-play-state: running;
	}
	
	/* 专辑封面图片调整 */
	.big-cover image {
		width: 100%;
	    height: 100%;
	    border-radius: 50%;
	    box-shadow: 0 0 1upx 1upx black;
	}
	
	/* 播放栏 */
	.play-area {
		position: fixed;
		bottom: 0;
	}
	
    /* 歌词栏高度 */
    .lyricList {
        height: 350upx;
        overflow: hidden;
    }

    /* ul列表区 */
    .lyricListContent {
        margin: 0;
        padding: 0;
        list-style-type: none;
        text-align: center;
        transition: margin .5s;
    }

    /* 每一项歌词 */
    .lyricListContent li {
        margin: 0;
        padding: 0;
        font-size: 25upx;
        line-height: 50upx;
    }

    /* 时间 */
    .text {
        width: 700upx;
        height: 50upx;
    }
    /* 播放时间 */
    .text-left {
        float: left;
    }
    /* 总时间 */
    .text-right {
        float: right;
    }

    .marboth {
        margin-top: 50upx;
        margin-bottom: 50upx;
    }
</style>